import 'dart:convert';

import 'package:app/common/product_card.dart';
import 'package:app/model/product_sale_out.dart';
import 'package:app/model/product_view_model.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:provider/provider.dart';
// 提供五套可选主题色
const Map<String, MaterialColor> _themesMap = <String, MaterialColor>{
  "魔幻蓝":Colors.blue,
  "基佬紫":Colors.deepPurple,
  "大便黄":Colors.orange,
  "草原绿":Colors.green,
  "艳丽红":Colors.red,
  "少女粉":Colors.pink,
};

const Map<String, MaterialColor> _actionMap = <String, MaterialColor>{
  "修改":Colors.blue,
  "删除":Colors.cyan,
};

class Global{
  static SharedPreferences _sharedPreferences;
  //static Profile profile = Profile();
  // 网络缓存对象
  // 产品操作
  static Map<String,MaterialColor> get actions =>_actionMap;
  // 可选的主题列表
  static Map<String,MaterialColor> get themes => _themesMap;

  // 当前主题
  static MaterialColor get currentTheme => _themesMap[getKVProfile("theme")];
  // 是否为release版
  //static bool get isRelease => bool.fromEnvironment("dart.vm.product");

  //初始化全局信息，会在APP启动时执行
  static Future init() async {
    _sharedPreferences = await SharedPreferences.getInstance();
    _sharedPreferences.setString("theme",getKVProfile("theme")==null ? "red":getKVProfile("theme"));
  }

  static Future<MaterialColor> changeTheme(String color) async {
    _sharedPreferences = await SharedPreferences.getInstance();
    _sharedPreferences.setString("theme",color);
    return _themesMap[getKVProfile("theme")];
  }
  // 持久化Profile信息
  static saveKVProfile(String key,String value) => _sharedPreferences.setString(key, value);

  // 获取Profile信息
  static dynamic getKVProfile(String key) =>  _sharedPreferences.get(key);

  // 持久化Profile信息
  static saveKJProfile(String key,String jsonString) => _sharedPreferences.setString(key, jsonString);

  // 获取Profile信息
  static dynamic getKJProfile(String key) =>  _sharedPreferences.get(key);

}

class GlobalData with ChangeNotifier {

  List<ProductViewModel> _listProduct = [];
  static List<ProductSaleOut> _listSaleOut = [];
  int _shopCartCount = 0;
  MaterialColor _currentTheme = _themesMap[Global.getKVProfile("theme")];

  dynamic calc(){
    //List<ProductViewModel> list = globalData.listProduct;
    int priceSale=0;
    int priceBig=0;
    String content="";
    _listProduct.forEach((product)=>{
      priceBig =priceBig+ int.parse(product.priceBig),
      priceSale =priceSale+ int.parse(product.priceSale),
      content =content+ "|"+product.productName
    });
    return {"priceBig":priceBig,"priceSale":priceSale,"content":content,"money":priceSale-priceBig};
  }

  static void initSaleOutList() async{
    List<ProductSaleOut> _listSaleOutTemp = [];
    var jsonArray = json.decode(Global.getKJProfile("listsaleOut"));
    jsonArray.forEach((x)=>{
      _listSaleOutTemp.add(new ProductSaleOut(dateTime:x['dateTime'],content:x['content'],priceBig: x['priceBig'],priceSale: x['priceSale'],money:x['money']))
    });
    _listSaleOut=_listSaleOutTemp;
  }

  get shopCartCount => _shopCartCount==0?"":_shopCartCount;
  get currentTheme => _currentTheme;
  get listProduct => _listProduct;
  get listSaleOut => _listSaleOut.reversed.toList();

  addShopCartCount(ProductViewModel product) {
    _listProduct.add(product);
    //print(_listProduct.toString());
    _shopCartCount++;
    notifyListeners();
  }
  minusShopCartCount(ProductViewModel product) {
    //_listProduct.remove(product);
    _listProduct.removeAt(listProduct.indexWhere((x)=>x.id==product.id));
    //print(_listProduct.toString());
    _shopCartCount--;
    notifyListeners();
  }

  saleOut(ProductSaleOut saleOut) {
    if(saleOut.content.isNotEmpty) {
      _listSaleOut.add(saleOut);
      _shopCartCount = 0;
      _listProduct=[];
      Global.saveKJProfile("listsaleOut",json.encode(_listSaleOut));
      //_listSaleOut=;
      notifyListeners();
    }
  }

  clearShopCartCount() {
    _shopCartCount = 0;
    _listProduct=[];
    notifyListeners();
  }

  changeTheme(value) async {
    _currentTheme = await Global.changeTheme(value);
    notifyListeners();
  }
}

class MyTab extends Tab{
  // MyTab({this.type, this.productList});
  MyTab({this.type, this.productList,String text}): super(text: text);

  String type;

  List<dynamic> productList;

  void setProductList(List<dynamic> productList){
    this.productList=productList;
  }

  String getType(){
    return this.type;
  }
}

class MainList with ChangeNotifier {

  static Map<String,MyTab> tabMap=new Map();

  static List<MyTab> myTabs=<MyTab>[
    new MyTab(text: "京卫本草",type:"jwbc"),
    new MyTab(text: "爱心神奇",type:"axsq"),
    new MyTab(text: "协和医院",type:"xhyy"),
    new MyTab(text: "肤倍佳",type:"fbj"),
    new MyTab(text: "医美",type:"ym"),
    new MyTab(text: "可丽金",type:"klj"),
    new MyTab(text: "益肤",type:"yf"),
    new MyTab(text: "新产品",type:"xcp"),
    new MyTab(text: "其他",type:"qt"),
  ];

  get getTabMaps =>tabMap;
  get getMyTabs =>myTabs;

  static Future getProductByType(String type) async {
    try {
      Response response = await Dio().get("http://106.54.126.84:8099/wx/getproductlistbytype/$type");
      return response.data;
    } catch (e) {
      print(e);
      //return null;
    }
  }

  void reloadAll() async {
    await Dio().get("http://106.54.126.84:8099/wx/reloadproductlist");
    getProductByType("jwbc").then((x)=>tabMap["jwbc"].setProductList(x));
    getProductByType("axsq").then((x)=>tabMap["axsq"].setProductList(x));
    getProductByType("xhyy").then((x)=>tabMap["xhyy"].setProductList(x));
    getProductByType("fbj").then((x)=>tabMap["fbj"].setProductList(x));
    getProductByType("ym").then((x)=>tabMap["ym"].setProductList(x));
    getProductByType("klj").then((x)=>tabMap["klj"].setProductList(x));
    getProductByType("yf").then((x)=>tabMap["yf"].setProductList(x));
    getProductByType("xcp").then((x)=>tabMap["xcp"].setProductList(x));
    getProductByType("qt").then((x)=>tabMap["qt"].setProductList(x));
    notifyListeners();
  }

  //重载数据
  void reloadByType(String type) async {
    getProductByType(type).then((x)=>{
      tabMap[type].setProductList(x),
        notifyListeners()
    });
  }

  static void initTabMap(){
    getProductByType("jwbc").then((x)=>{
      tabMap["jwbc"].setProductList(x),
    });
    myTabs.forEach((x)=>tabMap.putIfAbsent(x.getType(),()=>x));
  }
}
